package com.bootdo.xzl.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.search.TotalHits;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder.Type;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bootdo.xzl.dao.HousesInfoDao;
import com.bootdo.xzl.domain.HousesImgInfoDO;
import com.bootdo.xzl.domain.SecondhandGoodsDO;
import com.bootdo.xzl.service.SecondhandGoodsService;
import com.alibaba.fastjson.JSON;
import com.bootdo.common.dao.DictDao;
import com.bootdo.common.domain.DictDO;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.system.domain.UserDO;

/**
 * 二手物品
 * 
 * @author chenhuan
 * @email huan.chen@i-soft.com.cn
 * @date 2019-12-20 09:54:12
 */

@Controller
@RequestMapping("/xzl/secondhandGoods")
public class SecondhandGoodsController {

	@Autowired
	private SecondhandGoodsService secondhandGoodsService;

	@Autowired
	private RestHighLevelClient restHighLevelClient;

	@Autowired
	private DictDao dictDao;

	@Autowired
	private HousesInfoDao housesInfoDao;

	@GetMapping()
	@RequiresPermissions("xzl:secondhandGoods:secondhandGoods")
	String SecondhandGoods(Model model) {

		// 用户信息
		UserDO user = ShiroUtils.getUser();
		model.addAttribute("user", user);

		return "xzl/secondhandGoods/secondhandGoods";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("xzl:secondhandGoods:secondhandGoods")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<SecondhandGoodsDO> secondhandGoodsList = secondhandGoodsService.list(query);
		int total = secondhandGoodsService.count(query);
		PageUtils pageUtils = new PageUtils(secondhandGoodsList, total);
		return pageUtils;
	}

	@ResponseBody
	@GetMapping("/es/secondhandGoodsList")
	// @RequiresPermissions("xzl:buildingManagement:buildingManagement")
	public PageUtils managementList(@RequestParam Map<String, Object> params) {

		// 拼接检索条件
	    BoolQueryBuilder boolQueryBuilder = buildEsParam(params);

		if (params.containsKey("esText") && params.get("esText") != null) {
			if (params.get("esText").toString().equals("")) {
				QueryBuilder matchAll = QueryBuilders.matchAllQuery();
				boolQueryBuilder.must(matchAll);
			} else {
				QueryBuilder queryText = QueryBuilders.queryStringQuery("+" + params.get("esText").toString());
				boolQueryBuilder.must(queryText);
			}
		}

		if (params.containsKey("esText") && params.get("esText") != null) {
			if (params.get("esText").toString().equals("")) {
				QueryBuilder matchAll = QueryBuilders.matchAllQuery();
				boolQueryBuilder.filter(matchAll);
			} else {
		
				Map<String, Float> fields = new HashMap<String, Float>(8);
			      fields.put("secondhand_goods_count", 4.0f);
			      fields.put("secondhand_goods_atm", 3.0f);
			      fields.put("secondhand_goods_name", 2.0f);
			      fields.put("secondhand_goods_info", 1.0f);

					QueryBuilder entireReg = QueryBuilders.multiMatchQuery(params.get("esText").toString(), "secondhand_goods_name","secondhand_goods_atm")
				          .fields(fields)
				          .type(Type.CROSS_FIELDS)  //合并字段查询
				          .operator(Operator.AND);
					boolQueryBuilder.filter(entireReg);
			}
		}

		
		// 查询构造器
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		// 分页
		int offset = Integer.valueOf(params.get("offset").toString());
		int limit = Integer.valueOf(params.get("limit").toString());
		// 降序
		searchSourceBuilder.from(offset);
		searchSourceBuilder.sort("id", SortOrder.DESC);
		searchSourceBuilder.size(limit);
		searchSourceBuilder.query(boolQueryBuilder);
		// 创建查询器
		SearchRequest request = new SearchRequest("secondhandgoods");
		request.source(searchSourceBuilder);
		// 返回集合
		List<SecondhandGoodsDO> BuildingManagementList = null;
		List<HousesImgInfoDO> imageList = null;
		// 分页数量
		TotalHits totalHits = null;
		// 返回
		PageUtils pageUtils = null;
		// 查询
		try {
			//判断索引是否为空
			GetIndexRequest getIndexRequest = new GetIndexRequest("secondhandgoods");
			Boolean bln = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
			if(bln) {
				SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
				if (null != response) {
					totalHits = response.getHits().getTotalHits();// 总条数
					SearchHits searchHits = response.getHits();
					SearchHit[] hits = searchHits.getHits();
					BuildingManagementList = new ArrayList<>(hits.length);
					for (SearchHit hit : hits) {
						BuildingManagementList.add(JSON.parseObject(hit.getSourceAsString(), SecondhandGoodsDO.class));
					}
					if (BuildingManagementList != null && BuildingManagementList.size() > 0) {

						SearchRequest request1 = new SearchRequest("images");

						for (SecondhandGoodsDO SecondhandGoodsDO : BuildingManagementList) {

							BoolQueryBuilder boolQueryImages = QueryBuilders.boolQuery();

							QueryBuilder queryImages = QueryBuilders.matchQuery("office_id", SecondhandGoodsDO.getId());
							boolQueryImages.must(queryImages);

							QueryBuilder queryDelFlagImage = QueryBuilders.matchQuery("del_flag", "0");
							boolQueryImages.must(queryDelFlagImage);
							
							QueryBuilder queryimg_flg = QueryBuilders.matchQuery("img_flg", "1");
							boolQueryImages.must(queryimg_flg);

							SearchSourceBuilder searchSourceBuilderImages = new SearchSourceBuilder();
							searchSourceBuilderImages.query(boolQueryImages);
							request1.source(searchSourceBuilderImages);

							response = restHighLevelClient.search(request1, RequestOptions.DEFAULT);

							if (null != response) {
								imageList = new ArrayList<>(hits.length);
								SearchHits searchHits2 = response.getHits();
								SearchHit[] hits2 = searchHits2.getHits();
								imageList = new ArrayList<>(hits.length);
								for (SearchHit hit : hits2) {

									imageList.add(JSON.parseObject(hit.getSourceAsString(), HousesImgInfoDO.class));
								}
							}
							SecondhandGoodsDO.setHousesImgInfoList(imageList);
						}
					}
				}
				// 返回
				 pageUtils = new PageUtils(BuildingManagementList, Integer.valueOf(String.valueOf(totalHits.value)));
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return pageUtils;
	}
	/**
     *拼装查询条件
* @param query
* @return
*/
public static BoolQueryBuilder buildEsParam(Map<String, Object> params) {

 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

 //filter 效率比 must高的多 
 //删除区分
	boolQueryBuilder.filter(QueryBuilders.matchQuery("del_flag", "0"));

	// 类型
	if (params.containsKey("secondhandGoodsType") && params.get("secondhandGoodsType") != null
			&& StringUtils.isNotEmpty(params.get("secondhandGoodsType").toString())) {
		
		boolQueryBuilder.filter(QueryBuilders.matchQuery("secondhand_goods_type", params.get("secondhandGoodsType")));
	}
	
	// 金额
	if (params.containsKey("startMoney") && !params.containsKey("endMoney")) {
			boolQueryBuilder.filter(QueryBuilders.matchQuery("secondhand_goods_atm", params.get("startMoney")));
	}
	if (params.containsKey("startMoney") && params.containsKey("endMoney")) {
			boolQueryBuilder.filter(QueryBuilders.rangeQuery("secondhand_goods_atm").from(params.get("startMoney")).to(params.get("endMoney")));
	}
 return boolQueryBuilder;
}
	@GetMapping("/add")
	@RequiresPermissions("xzl:secondhandGoods:add")
	String add(Model model) {

		// 用户信息
		UserDO user = ShiroUtils.getUser();
		model.addAttribute("user", user);

		// 类型
		Map<String, Object> secondhandGoodsTypeParam = new HashMap<>();
		secondhandGoodsTypeParam.put("type", "secondhand_goods_type");
		List<DictDO> secondhandGoodsTypeList = dictDao.list(secondhandGoodsTypeParam);
		model.addAttribute("secondhandGoodsTypeList", secondhandGoodsTypeList);

		// 等级排名
		Map<String, Object> secondhandGoodsRankingParam = new HashMap<>();
		secondhandGoodsRankingParam.put("type", "officeRanking");
		List<DictDO> secondhandGoodsRankingList = dictDao.list(secondhandGoodsRankingParam);
		model.addAttribute("secondhandGoodsRankingList", secondhandGoodsRankingList);

		// 火热标记
		Map<String, Object> secondhandGoodsDegreeParam = new HashMap<>();
		secondhandGoodsDegreeParam.put("type", "officeKbn");
		List<DictDO> secondhandGoodsDegreeParamList = dictDao.list(secondhandGoodsDegreeParam);
		model.addAttribute("secondhandGoodsDegreeParamList", secondhandGoodsDegreeParamList);

		// 区域
		Map<String, Object> secondhandGoodsAreaParam = new HashMap<>();
		secondhandGoodsAreaParam.put("type", "area");
		List<DictDO> secondhandGoodsAreaList = dictDao.list(secondhandGoodsAreaParam);
		model.addAttribute("secondhandGoodsAreaList", secondhandGoodsAreaList);

		return "xzl/secondhandGoods/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("xzl:secondhandGoods:edit")
	String edit(@PathVariable("id") Integer id, Model model) {
		SecondhandGoodsDO secondhandGoods = secondhandGoodsService.get(id);
		model.addAttribute("secondhandGoods", secondhandGoods);

		// 用户信息
		UserDO user = ShiroUtils.getUser();
		model.addAttribute("user", user);

		// 类型
		Map<String, Object> secondhandGoodsTypeParam = new HashMap<>();
		secondhandGoodsTypeParam.put("type", "secondhand_goods_type");
		secondhandGoodsTypeParam.put("value", secondhandGoods.getSecondhandGoodsType());
		List<DictDO> secondhandGoodsTypeList = housesInfoDao.dictListByValue(secondhandGoodsTypeParam);
		model.addAttribute("secondhandGoodsTypeList", secondhandGoodsTypeList);

		// 等级排名
		Map<String, Object> secondhandGoodsRankingParam = new HashMap<>();
		secondhandGoodsRankingParam.put("type", "officeRanking");
		secondhandGoodsRankingParam.put("value", secondhandGoods.getSecondhandGoodsRanking());
		List<DictDO> secondhandGoodsRankingList = housesInfoDao.dictListByValue(secondhandGoodsRankingParam);
		model.addAttribute("secondhandGoodsRankingList", secondhandGoodsRankingList);

		// 火热标记
		Map<String, Object> secondhandGoodsDegreeParam = new HashMap<>();
		secondhandGoodsDegreeParam.put("type", "officeKbn");
		secondhandGoodsDegreeParam.put("value", secondhandGoods.getSecondhandGoodsDegree());
		List<DictDO> secondhandGoodsDegreeParamList = housesInfoDao.dictListByValue(secondhandGoodsDegreeParam);
		model.addAttribute("secondhandGoodsDegreeParamList", secondhandGoodsDegreeParamList);

		// 区域
		Map<String, Object> secondhandGoodsAreaParam = new HashMap<>();
		secondhandGoodsAreaParam.put("type", "area");
		secondhandGoodsAreaParam.put("value", secondhandGoods.getSecondhandGoodsArea());
		List<DictDO> secondhandGoodsAreaList = housesInfoDao.dictListByValue(secondhandGoodsAreaParam);
		model.addAttribute("secondhandGoodsAreaList", secondhandGoodsAreaList);

		return "xzl/secondhandGoods/edit";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("xzl:secondhandGoods:add")
	public R save(SecondhandGoodsDO secondhandGoods) {
		if (secondhandGoodsService.save(secondhandGoods) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("xzl:secondhandGoods:edit")
	public R update(SecondhandGoodsDO secondhandGoods) {
		secondhandGoodsService.update(secondhandGoods);
		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("xzl:secondhandGoods:remove")
	public R remove(Integer id) {
		SecondhandGoodsDO param = new SecondhandGoodsDO();
		param.setId(id);
		param.setDelFlag("1");
		if (secondhandGoodsService.update(param) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("xzl:secondhandGoods:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids) {
		if (secondhandGoodsService.batchUpdate(ids) > 0) {
			return R.ok();
		}
		return R.error();
	}

	// 详情接口
	@ResponseBody
	@GetMapping("/secondhandGoodsInfo")
	// @RequiresPermissions("xzl:housesInfo:housesInfo")
	public SecondhandGoodsDO housesInfo(@RequestParam("id") Integer id) {

		return secondhandGoodsService.secondhandGoodsInfo(id);
	}

}
